package com.example.yls.web_js2;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;

import java.util.Set;
//资料详情  https://www.jianshu.com/p/345f4d8a5cfa
//2.JS通过WebView调用 Android 代码
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity" ;
    private WebView my_webview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        my_webview=findViewById(R.id.my_webview);
        WebSettings webSettings=my_webview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setDefaultTextEncodingName("utf-8");

        /*2.方式3：通过 WebChromeClient 的onJsAlert()、onJsConfirm()、onJsPrompt（）方法
        *       回调拦截JS对话框alert()警告框、confirm()确认框、prompt（）提问框 消息
        */
        my_webview.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                Log.e(TAG, "alert message = " + message);
                Uri uri = Uri.parse(message);
                if (uri.getScheme().equals("js")) {
                    if (uri.getAuthority().equals("webview")) {
                        String func = uri.getQueryParameter("func");
                        if (func.equals("showDetail")) {
                            String id = uri.getQueryParameter("id");
                            Intent intent = new Intent(MainActivity.this,
                                    DetailActivity.class);
                            intent.putExtra("id", id);
                            startActivity(intent);

                        }
                    }
                }
                    return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                Uri uri = Uri.parse(message);
                if (uri.getScheme().equals("js")) {
                    if (uri.getAuthority().equals("webview")) {
                        String func = uri.getQueryParameter("func");
                        if (func.equals("getInfo")) {
                            final AlertDialog alertDialog=new AlertDialog.Builder(MainActivity.this)
                                    .setTitle("请选择性别")
                                    .setPositiveButton("帅哥", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            result.confirm();
                                            dialogInterface.cancel();
                                        }
                                    })
                                    .setNegativeButton("美女", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            result.cancel();
                                            dialogInterface.cancel();
                                        }
                                    }).create();
                            alertDialog.show();
                        }
                    }
                }
                return true;
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) {
                Uri uri = Uri.parse(message);
                if(uri.getScheme().equals("js")){
                    if(uri.getAuthority().equals("webview")){
                        String func=uri.getQueryParameter("func");
                        if(func.equals("getName")){
                            final EditText editText=new EditText(MainActivity.this);
                            AlertDialog alertDialog=new AlertDialog.Builder(MainActivity.this)
                                    .setTitle("请输入姓名")
                                    .setView(editText)
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            String name=editText.getText().toString();
                                            result.confirm(name);
                                            dialogInterface.cancel();
                                        }
                                    }).create();
                            alertDialog.show();
                        }
                    }
                }
                return true;
            }
        });

        //2.方式2：通过 WebViewClient 的方法shouldOverrideUrlLoading ()回调拦截 url
        my_webview.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e(TAG,"url="+url);
                Uri uri=Uri.parse(url);
                Log.e(TAG,"sheme = "+uri.getScheme());
                Log.e(TAG,"Authority = "+uri.getAuthority());

                if(uri.getScheme().equals("js")){
                    if(uri.getAuthority().equals("webview")){
                        /*Set<String> paramSet=uri.getQueryParameterNames();
                        for(String parm : paramSet){
                            String value=uri.getQueryParameter(parm);
                            Log.e(TAG,"param = "+parm+" value ="+value);
                        }*/
                        String func=uri.getQueryParameter("func");
                        if(func.equals("showDetail")){
                            String id=uri.getQueryParameter("id");
                            Intent intent=new Intent(MainActivity.this,
                                    DetailActivity.class);
                            intent.putExtra("id",id);
                            startActivity(intent);

                        }
                    }
                }
                return true;
            }
        });

        my_webview.loadUrl("file:///android_asset/test.html");
    }
}
